#include <common.h>

#if defined(MULTIPROGRAM) && !defined(TIME_SHARING)
# define MULTIPROGRAM_YIELD() yield()
#else
# define MULTIPROGRAM_YIELD()
#endif

#define NAME(key) \
  [AM_KEY_##key] = #key,

static const char *keyname[256] __attribute__((used)) = {
  [AM_KEY_NONE] = "NONE",
  AM_KEYS(NAME)
};
AM_GPU_CONFIG_T gpu ;
size_t serial_write(const void *buf, size_t offset, size_t len) {
  const char * temp = buf;
  for (size_t i = 0; i < len; i++)
  {
    putch(*temp++);
  }
  return len;
}

size_t events_read(void *buf, size_t offset, size_t len) {
  AM_INPUT_KEYBRD_T ev = io_read(AM_INPUT_KEYBRD);
  if (ev.keycode > 0)
  {
    sprintf(buf,"%s %s\n", ev.keydown ? "kd " : "ku ",keyname[ev.keycode]);
    return len;    
  }
  else
  {
    return 0;
  }
  
}

size_t dispinfo_read(void *buf, size_t offset, size_t len) {
  char dispinfo_c[256];
  char *temp=dispinfo_c;
  temp += sprintf(temp,"PRESENT: %d\n",gpu.present) ;
  temp += sprintf(temp,"HAS_ACCEL: %d\n",gpu.has_accel) ;
  temp += sprintf(temp,"WIDTH: %d\n",gpu.width) ;
  temp += sprintf(temp,"HEIGHT: %d\n",gpu.height) ;
  temp += sprintf(temp,"VMEMSZ: %d\n",gpu.vmemsz) ;
  memcpy(buf,dispinfo_c,len);
  return len;
}
#define N   32
// static uint32_t color_buf[32 * 32];
size_t fb_write(const void *buf, size_t offset, size_t len) {
  int x , y ,w,h;
  y = offset &0xfff;
  x = (offset >> 12) & 0xfff;
  w = len & 0xfff;
  h = (len >> 12) & 0xfff;
  if (x+w > 400)
  {
    printf("offset = 0x%lx,len =0x%lx x = %d y = %d w = %d h = %d\n",offset,len,x,y,w,h);
    assert(0);
  }
   if (y+h > 300)
  {
    printf("offset = 0x%lx,len =0x%lx x = %d y = %d w = %d h = %d\n",offset,len,x,y,w,h);
    assert(0);
    
  }
  io_write(AM_GPU_FBDRAW, x , y , (void *)buf, w, h, true);
  return len;
}

void init_device() {
  Log("Initializing devices...");
  ioe_init();
  gpu =  io_read(AM_GPU_CONFIG);
  assert (gpu.width != 0);
}
